//
//  PlazzTableView.m
//  SoundPill
//
//  Created by 宋旭东 on 15/7/3.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "PlazzTableView.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "plaza_viewModel.h"
#import "ContentTableViewCell.h"
#import "NewestTopicTableViewCell.h"
#import "DCPicScrollView.h"
#import "DCWebImageManager.h"
#import "UIImageView+WebCache.h"
#define kDeviceHeight [UIScreen mainScreen].bounds.size.height
#define kDeviceWidth  [UIScreen mainScreen].bounds.size.width

@interface PlazzTableView ()<UITableViewDelegate, UITableViewDataSource,MJRefreshBaseViewDelegate>
{
    int page;
    int lastPage;
    int pages;
    NSString *_filePath;
    NSArray *banerArray;
    UIImageView *banerButton;
    DCPicScrollView *baner;
    MJRefreshHeaderView *header;
    MJRefreshFooterView *fotter;
}
@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray *plazzArray;
@end

@implementation PlazzTableView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.plazzArray = [[NSMutableArray alloc] init];
        [self createTableview];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"plazz"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadDataWithResponseObject:content pag:1];
            page = 1;
        } else {
            [header beginRefreshing];
        }
    }
    return self;
}
- (void)createTableview
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    [self addSubview:_tableview];
    
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
    //刷新控件
    header = [MJRefreshHeaderView header];
    header.scrollView = _tableview;
    header.delegate = self;

    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _tableview;
    fotter.delegate = self;
}
- (void)createTableViewHeader:(NSArray *)array;
{
    
    //    NSArray *UrlStringArray = [NSArray arrayWithObjects:@"http://p1.qqyou.com/pic/UploadPic/2013-3/19/2013031923222781617.jpg", @"http://p1.qqyou.com/pic/UploadPic/2013-3/19/2013031923222781617.jpg",
    //        @"http://cdn.duitang.com/uploads/item/201409/27/20140927192649_NxVKT.thumb.700_0.png",nil];
    NSMutableArray *urlArray = [[NSMutableArray alloc] init];
    for (NSDictionary *dic in array) {
        NSString *url = [dic valueForKeyPath:@"image"];
        [urlArray addObject:url];
    }
    if (urlArray.count > 1) {
        if (!baner) {
            baner = [DCPicScrollView picScrollViewWithFrame:CGRectMake(0, 0, self.frame.size.width, (self.frame.size.width) * 0.40) WithImageUrls:urlArray];
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, baner.frame.size.height)];
            view.backgroundColor = [UIColor whiteColor];
            //            [view addSubview:baner];
            _tableview.tableHeaderView = baner;
        }
        baner.placeImage = [UIImage imageNamed:@"place.png"];
        
        //图片被点击事件,当前第几张图片被点击了,和数组顺序一致
        
        [baner setImageViewDidTapAtIndex:^(NSInteger index) {
            printf("第%zd张图片\n",index);
            NSNumber *type = [array[index] valueForKey:@"type"];
            switch (type.intValue) {
                case 1://作品
                {
                    NSString *workID = [array[index] valueForKey:@"detail"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:workID];
                }
                    break;
                case 2://话题
                {
                    NSString *topic = [array[index] valueForKey:@"detail"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"searchTopic" object:[NSString stringWithFormat:@"#%@#", topic]];
                }
                    break;
                default:
                    break;
            }
        }];
        
        //default is 2.0f,如果小于0.5不自动播放
        baner.AutoScrollDelay = 5.0f;
        //    picView.textColor = [UIColor redColor];
        //下载失败重复下载次数,默认不重复,
        [[DCWebImageManager shareManager] setDownloadImageRepeatCount:1];
        //图片下载失败会调用该block(如果设置了重复下载次数,则会在重复下载完后,假如还没下载成功,就会调用该block)
        //error错误信息
        //url下载失败的imageurl
        [[DCWebImageManager shareManager] setDownLoadImageError:^(NSError *error, NSString *url) {
//            NSLog(@"%@",error);
        }];
    } else {
        if (!banerButton) {
            banerButton = [[UIImageView alloc] initWithFrame:CGRectMake(15, 0, self.frame.size.width - 30, (self.frame.size.width - 30) * 0.40)];
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, banerButton.frame.size.height)];
            view.backgroundColor = [UIColor whiteColor];
            [view addSubview:banerButton];
            banerButton.userInteractionEnabled = YES;
            _tableview.tableHeaderView = view;
        }
        [banerButton setImageWithURL:[NSURL URLWithString:[urlArray firstObject]] placeholderImage:nil];
        UITapGestureRecognizer *recognaizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onlyOneBannerTap:)];
        [banerButton addGestureRecognizer:recognaizer];
    }
}
- (void)onlyOneBannerTap:(UITapGestureRecognizer *)recognaizer
{
    NSNumber *type = [banerArray[0] valueForKey:@"type"];
    switch (type.intValue) {
        case 1://作品
        {
            NSString *workID = [banerArray[0] valueForKey:@"detail"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:workID];
        }
            break;
        case 2://话题
        {
            NSString *topic = [banerArray[0] valueForKey:@"detail"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"searchTopic" object:[NSString stringWithFormat:@"#%@#", topic]];
        }
            break;
        default:
            break;
    }
}
#pragma mark -
#pragma mark tableview 协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _plazzArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *resonStr = nil;
    if (_plazzArray.count > 0) {
        if ([_plazzArray[indexPath.row] isKindOfClass:[plaza_viewModel class]]) {
            plaza_viewModel *model = _plazzArray[indexPath.row];
            if (![model.reason isKindOfClass:[NSNull class]]) {
                resonStr = model.reason;
            } else {
                resonStr = @"暂无推荐理由";
            }
            CGFloat height = [self heightForText:resonStr];
            if (model.signArray.count > 0) {
                if ([UIScreen mainScreen].bounds.size.width == 320) {
                    return 0.4136 * [UIScreen mainScreen].bounds.size.height + height + 15;
                } else if ([UIScreen mainScreen].bounds.size.height == 667) {
                    return 0.4236 * [UIScreen mainScreen].bounds.size.height + height + 15;
                } else {
                    return 0.4336 * [UIScreen mainScreen].bounds.size.height + height + 15;
                }
            } else {
                return 0.3937 * [UIScreen mainScreen].bounds.size.height + height;
            }
        } else {
            return 230;
        }
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    if (_plazzArray.count > 0 && [_plazzArray[indexPath.row] isKindOfClass:[NSArray class]]) {
        static NSString *cellIdentifier = @"topicCell";
        NewestTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[NewestTopicTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier topicArray:_plazzArray[indexPath.row]];
        }
        //        cell.topicArray = [NSArray arrayWithArray:];
        return cell;
    } else {
    static NSString *cellIdentifier2 = @"cell2";
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
    if (cell == nil) {
        cell = [[ContentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier2];
    }
    [cell.tagView removeFromSuperview];
    if (_plazzArray.count>0) {
        cell.plazadataModel = _plazzArray[indexPath.row];
    }
    //创建标签视图
    cell.tagView = [[groundTagsView alloc]initWithFrame:CGRectZero];
    [cell.tagView createTagView:cell.plazadataModel.signArray];
    [cell addSubview:cell.tagView];
    return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    plaza_viewModel *mod = _plazzArray[indexPath.row];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:mod.CinemeID];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
#pragma mark -
#pragma mark 网络请求
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_plazzArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            fotter.hidden = YES;
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    
}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    //    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/works?p=%d", pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self reloadDataWithResponseObject:responseObject pag:pag];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
        });
        if (pag == 1) {
            //            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)reloadDataWithResponseObject:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSDictionary *dic = [bigDic valueForKey:@"data"];
    for (NSDictionary *dict in dic) {
        plaza_viewModel *model = [[plaza_viewModel alloc] init];
        model.CinemeID = [dict objectForKey:@"id"];
        //
        model.UserID = [dict objectForKey:@"uid"];
        //头像
        model.headImageURL = [[dict valueForKey:@"user"] valueForKey:@"avatar"];
        //NSLog(@"--%@",[item objectForKey:@"avatar"]);
        //名字
        model.personName = [[dict valueForKey:@"user"] valueForKey:@"username"];
        //标签
        model.signArray =  [dict objectForKey:@"tags"];
        //上传日期
        model.releaseDate = [dict objectForKey:@"created_at"];
        //标题
        model.title = [dict objectForKey:@"title"];
        //作品预览图
        model.worksImageURL = [dict objectForKey:@"cover"];
        //播放次数
        model.playTimes = [dict objectForKey:@"play_count"];
        //点按数量（心）
        model.heartCount = [dict objectForKey:@"love_count"];
        model.reason = [dict objectForKey:@"reason"];
        //时长
        model.duration = [dict objectForKey:@"duration"];
        if([dict objectForKey:@"liked"]){
            // NSLog(@"%@",[item objectForKey:@"liked"]);
            model.isLike = [[dict objectForKey:@"liked"] boolValue];
        }
        model.blue = [dict valueForKey:@"blue"];
        model.black = [dict valueForKey:@"black"];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_plazzArray addObject:model];
    }
    NSDictionary *meta = [bigDic valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            fotter.hidden = YES;
        }
        if (pag == 1) {
            if ([meta valueForKey:@"topicnum"] != nil) {
                NSInteger topicnum = [[meta valueForKey:@"topicnum"] integerValue];
                [_plazzArray insertObject:[meta valueForKey:@"topic"] atIndex:topicnum];
                
            }
            
            
            if ([meta objectForKey:@"banner"]) {
                banerArray = [meta objectForKey:@"banner"];
                [self createTableViewHeader:banerArray];
            } else {
                
            }
        }
    }
    [_tableview reloadData];
}
#pragma mark -
- (CGFloat)heightForText:(NSString *)text
{
    CGSize size = CGSizeMake(kDeviceWidth - 59, 2000);
    if ([UIScreen mainScreen].bounds.size.width == 320) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:12.0f] forKey:NSFontAttributeName];
        
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        return frame.size.height;
    } else if ([UIScreen mainScreen].bounds.size.height == 667) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0f] forKey:NSFontAttributeName];
        
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        return frame.size.height;
    } else {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:16.0f] forKey:NSFontAttributeName];
        
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];
        return frame.size.height;
    }

}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
